// 存储最新的分析结果
let lastAnalysisResult = null;
let mediaRecorder = null;
let audioChunks = [];
let recordingTimer = null;
let startTime = null;

// 在 analyzeAudio 函数顶部添加标签映射
const labelMap = {
    'ad': '广告引流',
    'violence': '暴恐内容',
    'political_content': '涉政内容',
    'specified_speaking': '特定声音',
    'specified_lyrics': '特定歌曲',
    'sexual_content': '色情内容',
    'sexual_sounds': '呻吟声音',
    'contraband': '违禁内容',
    'profanity': '辱骂内容',
    'religion': '宗教内容',
    'cyberbullying': '网络暴力',
    'negative_content': '不良内容',
    'nontalk': '静音音频',
    'C_customized': '用户库命中'
};

document.addEventListener('DOMContentLoaded', function() {
    const dropZone = document.getElementById('dropZone');
    const audioInput = document.getElementById('audioInput');
    const audioPreview = document.getElementById('audioPreview');
    const audioPlayer = document.getElementById('audioPlayer');
    const audioDuration = document.getElementById('audioDuration');
    const audioSize = document.getElementById('audioSize');
    const analyzeBtn = document.getElementById('analyzeBtn');
    const uploadForm = document.getElementById('uploadForm');
    const recordBtn = document.getElementById('recordBtn');
    const recordTime = document.getElementById('recordTime');

    // 阻止表单默认提交
    uploadForm.addEventListener('submit', (e) => {
        e.preventDefault();
        return false;
    });

    // 录音按钮点击事件
    recordBtn.addEventListener('click', async () => {
        if (!mediaRecorder || mediaRecorder.state === 'inactive') {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                startRecording(stream);
            } catch (err) {
                console.error('录音权限获取失败:', err);
                alert('无法访问麦克风，请确保已授予录音权限。');
            }
        } else {
            stopRecording();
        }
    });

    // 点击上传区域触发文件选择
    dropZone.addEventListener('click', () => audioInput.click());

    // 处理文件选择
    audioInput.addEventListener('change', handleFileSelect);

    // 添加分析按钮的点击事件监听
    analyzeBtn.addEventListener('click', (e) => {
        e.preventDefault();
        analyzeAudio();
    });

    // 处理拖放
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.classList.remove('dragover');
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            audioInput.files = files;
            handleFileSelect({ target: audioInput });
        }
    });

    // 音频加载完成后更新时长信息
    audioPlayer.addEventListener('loadedmetadata', function() {
        const duration = audioPlayer.duration;
        const minutes = Math.floor(duration / 60);
        const seconds = Math.floor(duration % 60);
        audioDuration.textContent = `时长：${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    });
});

// 处理文件选择
function handleFileSelect(event) {
    console.log('handleFileSelectddddddddd');
    
    const file = event.target.files[0];
    if (!file) return;

    // 验证文件类型
    const validTypes = ['audio/mp3', 'audio/wav', 'audio/x-m4a', 'audio/mpeg'];
    if (!validTypes.includes(file.type)) {
        alert('请选择有效的音频文件（MP3, WAV, M4A）');
        return;
    }

    // 验证文件大小（50MB限制）
    if (file.size > 50 * 1024 * 1024) {
        alert('文件大小超过50MB限制');
        return;
    }

    // 更新音频大小显示
    const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
    audioSize.textContent = `大小：${sizeMB} MB`;

    // 预览音频
    const audioPreview = document.getElementById('audioPreview');
    const audioPlayer = document.getElementById('audioPlayer');
    console.log(file, 'file ');
    
    audioPlayer.src = URL.createObjectURL(file);
    audioPreview.style.display = 'block';
    
}

// 获取服务类型
function getServiceType(selectedType) {
    return selectedType;  // 直接返回选择的值，因为已经是正确的服务类型
}

// 分析音频
async function analyzeAudio() {
    const audioInput = document.getElementById('audioInput');
    const audioType = document.getElementById('audioType');
    const resultArea = document.getElementById('analysisResult');
    const downloadBtn = document.getElementById('downloadBtn');
    const analyzeBtn = document.getElementById('analyzeBtn');
    const audioPreview = document.getElementById('audioPreview');
    
    if (!audioInput.files || audioInput.files.length === 0) {
        alert('请先选择音频文件！');
        return;
    }

    // 显示加载状态
    resultArea.innerHTML = `
        <div style="text-align: center; padding: 20px;">
            <p>正在分析音频，请稍候...</p>
            <p style="color: #666; font-size: 0.9em;">
                ${audioType.value === 'live_stream_detection' ? 
                    '直播内容分析可能需要一些时间，请耐心等待' : 
                    '音频分析可能需要一些时间，请耐心等待'}
            </p>
        </div>
    `;
    downloadBtn.style.display = 'none';
    analyzeBtn.disabled = true;

    try {
        const formData = new FormData();
        formData.append('audio', audioInput.files[0]);
        formData.append('serviceType', getServiceType(audioType.value));

        const response = await fetch('http://localhost:5000/api/analyze-audio', {
            method: 'POST',
            body: formData,
            headers: {
                'Accept': 'application/json'
            }
        });

        const data = await response.json();
        console.log('完整API响应:', data);  // 添加调试日志

        if (data.code !== 200) {
            throw new Error(data.error || '请求失败');
        }

        const result = data.data;
        const riskLevel = result.RiskLevel || 'none';  // 使用正确的字段名
        const sliceDetails = result.SliceDetails || [];
        const firstSlice = sliceDetails[0] || {};

        // 更新风险等级显示
        const riskLevelMap = {
            'none': '无风险',
            'low': '低风险', 
            'medium': '中风险',
            'high': '高风险'
        };

        resultArea.innerHTML = `
            <div style="padding: 20px; line-height: 1.8;">
                <div style="margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px;">
                    <h4 style="color: #1890ff; margin: 0;">基础信息</h4>
                    <div style="margin-top: 8px;">
                        <span style="color: #666;">风险等级：</span>
                        <span style="color: ${riskLevel === 'high' ? '#ff4d4f' : riskLevel === 'medium' ? '#faad14' : '#52c41a'}">
                            ${riskLevelMap[riskLevel] || '未知'}
                        </span>
                    </div>
                </div>

                <div style="margin: 15px 0; border-bottom: 1px solid #eee; padding-bottom: 10px;">
                    <h4 style="color: #1890ff; margin: 0 0 10px 0;">识别内容</h4>
                    <div style="background: #f8f9fa; padding: 10px; border-radius: 4px;">
                        ${firstSlice.Text || '无识别文本'}
                    </div>
                </div>

                <div style="margin: 15px 0;">
                    <h4 style="color: #1890ff; margin: 0 0 10px 0;">风险详情</h4>
                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                        <div>
                            <span style="color: #666;">风险类型：</span>
                            ${(firstSlice.Labels || '').split(',').map(label => {
                                const cleanedLabel = label.trim().toLowerCase();
                                return `
                                    <span style="display: inline-block; background: #fff1f0; color: #ff4d4f; 
                                        padding: 2px 8px; border-radius: 4px; margin: 2px;">
                                        ${labelMap[cleanedLabel] || cleanedLabel.replace(/_/g, ' ')}
                                    </span>
                                `;
                            }).join('')}
                        </div>
                        <div>
                            <span style="color: #666;">风险关键词：</span>
                            ${(firstSlice.RiskWords || '').split(',').map(word => `
                                <span style="display: inline-block; background: #fff7e6; color: #fa8c16; 
                                    padding: 2px 8px; border-radius: 4px; margin: 2px;">
                                ${word.trim() || '无'}
                                </span>
                            `).join('')}
                        </div>
                        <div>
                            <span style="color: #666;">检测时段：</span>
                            ${firstSlice.StartTime || 0} - ${firstSlice.EndTime || 0}秒
                        </div>
                        <div>
                            <span style="color: #666;">风险提示：</span>
                            ${(firstSlice.RiskTips || '').split(',').map(tip => `
                                <span style="display: inline-block; background: #f6ffed; color: #52c41a; 
                                    padding: 2px 8px; border-radius: 4px; margin: 2px;">
                                ${tip.trim() || '无'}
                                </span>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 更新全局变量
        lastAnalysisResult = {
            检测时间: new Date().toLocaleString(),
            检测类型: document.getElementById('audioType').value === 'audio_media_detection' ? '音视频媒体检测' : '社交娱乐直播检测',
            风险等级: riskLevelMap[riskLevel] || '未知',
            识别文本: firstSlice.Text || '无识别文本',
            风险类型: (firstSlice.Labels || '').split(',').map(label => {
                const cleanedLabel = label.trim().toLowerCase();
                return labelMap[cleanedLabel] || cleanedLabel.replace(/_/g, ' ');
            }).filter(Boolean),
            风险关键词: (firstSlice.RiskWords || '').split(',').map(word => word.trim()).filter(Boolean),
            检测时段: `${firstSlice.StartTime || 0}-${firstSlice.EndTime || 0}秒`,
            风险提示: (firstSlice.RiskTips || '').split(',').map(tip => tip.trim()).filter(Boolean)
        };

        downloadBtn.style.display = 'block';

    } catch (error) {
        resultArea.innerHTML = `
            <div style="color: #ff4d4f; padding: 20px; text-align: center; background: #fff2f0; border-radius: 8px;">
                <p>分析过程中出现错误：</p>
                <p>${error.message}</p>
                <p style="font-size: 0.9em; margin-top: 10px;">
                    请检查音频格式和大小，或稍后重试
                </p>
            </div>
        `;
        console.error('Error:', error);
        downloadBtn.style.display = 'none';
    } finally {
        analyzeBtn.disabled = false;  // 恢复分析按钮
        // 确保音频预览区域保持可见
        audioPreview.style.display = 'block';
    }
}

// 下载结果功能
function downloadResult() {
    if (!lastAnalysisResult) {
        alert('请先完成分析再下载结果');
        return;
    }

    try {
        const blob = new Blob(
            [JSON.stringify(lastAnalysisResult, null, 2)], 
            { type: 'application/json;charset=utf-8' }
        );
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `语音分析结果_${new Date().toISOString().slice(0,19).replace(/[:-]/g, '')}.json`;
        link.style.display = 'none';
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        URL.revokeObjectURL(link.href);
    } catch (error) {
        console.error('下载失败:', error);
        alert('文件下载失败，请检查控制台日志');
    }
}

// 开始录音
function startRecording(stream) {
    audioChunks = [];
    mediaRecorder = new MediaRecorder(stream);
    startTime = Date.now();

    mediaRecorder.addEventListener('dataavailable', event => {
        audioChunks.push(event.data);
    });

    mediaRecorder.addEventListener('stop', () => {
        const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
        const file = new File([audioBlob], 'recorded_audio.wav', { type: 'audio/wav' });
        
        // 更新音频预览
        const audioPreview = document.getElementById('audioPreview');
        const audioPlayer = document.getElementById('audioPlayer');
        audioPlayer.src = URL.createObjectURL(audioBlob);
        audioPreview.style.display = 'block';

        // 更新文件大小显示
        const sizeMB = (audioBlob.size / (1024 * 1024)).toFixed(2);
        document.getElementById('audioSize').textContent = `大小：${sizeMB} MB`;

        // 将录音文件添加到文件输入
        const dataTransfer = new DataTransfer();
        dataTransfer.items.add(file);
        document.getElementById('audioInput').files = dataTransfer.files;

        // 停止所有音轨
        stream.getTracks().forEach(track => track.stop());
    });

    // 更新UI
    const recordBtn = document.getElementById('recordBtn');
    const recordTime = document.getElementById('recordTime');
    recordBtn.classList.add('recording');
    recordBtn.innerHTML = '<span class="record-icon">●</span> 停止录音';
    recordTime.style.display = 'inline';

    // 更新录音时间
    recordingTimer = setInterval(updateRecordingTime, 1000);

    mediaRecorder.start();
}

// 停止录音
function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
        clearInterval(recordingTimer);

        // 更新UI
        const recordBtn = document.getElementById('recordBtn');
        const recordTime = document.getElementById('recordTime');
        recordBtn.classList.remove('recording');
        recordBtn.innerHTML = '<span class="record-icon">●</span> 开始录音';
        recordTime.style.display = 'none';
        recordTime.textContent = '00:00';
    }
}

// 更新录音时间显示
function updateRecordingTime() {
    if (!startTime) return;

    const recordTime = document.getElementById('recordTime');
    const elapsed = Math.floor((Date.now() - startTime) / 1000);
    const minutes = Math.floor(elapsed / 60);
    const seconds = elapsed % 60;
    recordTime.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
} 